import time
from typing import List

import requests
from playwright.sync_api import Page,sync_playwright, expect
import schedule
import time




config={
    "user":"195277",#账号
    "password":"qaz520131415",#密码
    "cardNO":"2259480080",#卡号
    "time":["18","19"],#场地小时
    "date":"2023-05-16"#日期
}
#一共8个场地
startNo=3
maxNo=8
orderPreix="20060709000"
orderPreixChinese="羽毛球0"
orderEndChinese="时"
venueId="200606060005"
venueName="体育馆"
payType="XJ"


loginURL="https://m.51hlife.cn/";
orderURL="https://m.51hlife.cn/2c/COrder/selectOrderrevisionList?categoryType=cg"
def work():
    with sync_playwright() as p:
        browser = p.webkit.launch()
        context = browser.new_context()
        page = context.new_page()
        page.goto(loginURL);
        time.sleep(1)
        page.locator("#username").fill(config["user"])
        time.sleep(1)
        page.locator("#password").fill(config["password"])
        time.sleep(1)
        page.locator("body > div > div:nth-child(3) > p").click()
        page.content();
        for i in range(0,10):
            cookies = context.cookies()
            if len(cookies)>3:
                break
            print(len(cookies))
            time.sleep(2)
            if len(page.locator("body > div > div:nth-child(3) > p").all())>0:
                page.locator("body > div > div:nth-child(3) > p").click()
            page.locator('body').click()
            page.content();
        if len(cookies) <= 3:
            print(cookies)
            print(page.content())
            raise Exception("failed");
        print("登录完成")
        cookieList=map(lambda x:x["name"]+"="+x["value"],cookies)
        cookiesStr="; ".join(cookieList)
        #循环8个场地
        flag=True
        while flag:
            for i in range(0,maxNo):
                siteNo=(i+startNo)%maxNo+1
                print("sitNo is "+str(siteNo))
                status=requestURL(siteNo,config["time"],cookiesStr)
                if status:
                    #确认订单
                    page.goto(orderURL)
                    orderlist=page.get_by_text(config["date"]).all()
                    if len(orderlist)==0:
                        print("no exist")
                    else:
                        print("exist")
                        flag=False
                    break
                else:
                    continue
            time.sleep(1)

def requestURL(siteNo,timeList:List[str],cookie):
    url = "https://m.51hlife.cn/2c/vm/insertOrderVenuePay"
    strList=map(lambda x:orderPreix+str(siteNo+1)+"_"+x,timeList)
    projectList=map(lambda x:orderPreixChinese+str(siteNo)+"_"+x+orderEndChinese,timeList)
    price=len(timeList)*10;
    data = {
        "str": ','.join(strList),
        "price": price,
        "payType":"XJ",
        "cardNo":config["cardNO"],
        "date":config["date"],
        "peoject":','.join(projectList),
        "venueId":"200606060005",
        "venueName":"体育馆"
    }  # formdata格式的数据
    headers = {
        "Content-Type": "application/x-www-form-urlencoded",
        "content-Encoding": "gzip",
        "cookie":cookie,
        "origin":"https://m.51hlife.cn",
        "referer":"https://m.51hlife.cn/2c/vm/venuPay",
        "x-requested-with":"XMLHttpRequest"
    }  # 设置请求头
    response = requests.post(url, data=data, headers=headers)  # 发送POST请求
    data = response.text  # 获取响应文本
    print("response is")
    print(data)
    if response.status_code==200:
        return True
    return False
def dowrok():
    try:
        work()
    except Exception as e:
        print("Exception",e)
        dowrok()
if __name__ == '__main__':
    dowrok();
    # schedule.every().day.at("11:58").do(dowrok)
    # while True:
    #     schedule.run_pending()
    #     t
    #     ime.sleep(1)
